<?php defined('BASEPATH') OR die('No direct access allowed.');
/**
 * Description of Accounts
 *
 * Created on Jan. 17, 2011
 * @author Ramon Gutierrez
 * @copyright Bitstop Network Services Inc.
 * @version 0.1
 */
class Accounts extends Controller {
	function Accounts()	{
		parent::Controller();
		global $header, $data;
		
		// Check if user is logged in
		if(!$this->session->userdata('account_id') ||
		($this->session->userdata('account_type') != 'site_admin' && $this->session->userdata('account_type') != 'company')) {
			redirect(site_url(), 'refresh');
		}
		
		// Header variables
		$header['extras'] = "";
		$header['grid'] = false;
		$header['title'] = $this->lang->line('title_accounts');
		$data['module'] = 'accounts';
		
		// Include global models for this module
		$this->load->model('accounts_model');
	}
	
	function index() {
		global $header, $data;
		
		// Load grid helper
		$this->load->helper('flexigrid');
		
		// Template variables
		$header['grid'] = true;
							
		// Load up that header!
		$this->load->view('header', $header);
		
		// Load the sidebar
		$this->load->view('sidebar-left', $data);
		
		// Flexigrid stuff
		if($this->session->userdata('account_type') == 'site_admin') {
			$colModel['account_id'] = array('', 50, TRUE, 'left', 0);
			$colModel['last_name'] = array('Last Name', 150, TRUE, 'left', 2);
			$colModel['first_name'] = array('First Name', 150, TRUE, 'left', 1);
			$colModel['username'] = array('Username', 140, TRUE, 'left', 1);
			$colModel['account_type'] = array('Account Type', 100, TRUE, 'left', 1);
			$colModel['name'] = array('Company', 100, TRUE, 'left', 1);
			$colModel['actions'] = array('Actions', 100, FALSE, 'left', 0);
		} else {
			$colModel['account_id'] = array('', 50, TRUE, 'left', 0);
			$colModel['last_name'] = array('Last Name', 150, TRUE, 'left', 2);
			$colModel['first_name'] = array('First Name', 150, TRUE, 'left', 1);
			$colModel['username'] = array('Username', 140, TRUE, 'left', 1);
			$colModel['account_type'] = array('Account Type', 100, TRUE, 'left', 1);
			$colModel['actions'] = array('Actions', 100, FALSE, 'left', 0);
		}
		
		// Confirm Flexigrid parameters
		$gridParams = array(
							'width' => 'auto',
							'height' => 'auto',
							'rp' => 50,
							'rpOptions' => '[10,15,20,25,50]',
							'pagestat' => 'Displaying: {from} to {to} of {total} items.',
							'blockOpacity' => 0.5,
							'title' => "<' + 'img src=\"" . site_url('images/accounts.png') . "\" alt=\"\" /> Accounts",
							'showTableToggleBtn' => false
						   );
		
		// Create Flexigrid buttons
		if($this->session->userdata('account_type') == 'company') {
			$buttons[] = array('New Agent', 'new', 'the_grid');
			$buttons[] = array('separator');
		}
		
		$buttons[] = array('Select All', 'select', 'the_grid');
		$buttons[] = array('De-select All', 'deselect', 'the_grid');
		$buttons[] = array('separator');
		$buttons[] = array('Batch Edit', 'edit', 'the_grid');

		// Build the grid!
		$grid_js = build_grid_js('the_grid', site_url("ajax/accounts_getrows/" . ($this->session->userdata('account_type') == 'company' ? $this->session->userdata('client_id') : "")), $colModel, 'last_name', 'asc', $gridParams, $buttons);
		$data['the_grid'] = $grid_js;
		
		// Dish out the meat
		$this->load->view('grid-index', $data);
		
		// Let's see that footer!
		$this->load->view('footer');
	}
	
	function edit($items) {
		global $header, $data;
		
		// Load local model
		$this->load->model('branches_model');
		$this->load->model('services_model');
		
		// Build the ID array
		$item_array = array_unique(explode(":", $items));
		
		// Template variables
		$header['extras'] = '<link href="' . site_url('css/jquery.asmselect.css') . '" rel="stylesheet" type="text/css" />' . "\n" .
							'<script type="text/javascript" src="' . site_url('js/jquery.asmselect.js') . '"></script>' . "\n" .
							'<script type="text/javascript">' . "\n" .
							'// <![CDATA[' . "\n" .
							'  $(document).ready(function() {' . "\n" .
							'    var options = {' . "\n" .
							'        target:         "#response",' . "\n" .
							'        success:        showResponse' . "\n" .
							'    };' . "\n\n" .
							'    $("#theform").ajaxForm(options);' . "\n" .
							'    $("select[multiple]").asmSelect({' . "\n" .
							'        addItemTarget: "bottom",' . "\n" .
							'        animate: true' . "\n" .
							'    });' . "\n" .
							'    function showResponse(responseText, statusText) {' . "\n" .
							'      $("#response").html(responseText).show();' . "\n" .
							'      if(responseText == "Update successful") {' . "\n" .
							'        $("#response").css("border", "1px solid #c8fb6e");' . "\n" .
							'        $("#response").css("backgroundColor", "#eaffb9");' . "\n" .
							'        window.scrollTo(0,0);' . "\n" .
							'        alert(responseText);' . "\n" .
							'        window.location = "' . site_url($data['module']) . '/";' . "\n" .
							'        //alert(responseText);' . "\n" .
							'      } else {' . "\n" .
							'        $("#response").css("border", "1px solid #fa4646");' . "\n" .
							'        $("#response").css("backgroundColor", "#fabfbf");' . "\n" .
							'        submitted = false;' . "\n" .
							'        window.scrollTo(0,0);' . "\n" .
							'      }' . "\n" .
							'    };' . "\n" .
							'  });' . "\n" .
							'// ]]>' . "\n" .
							'</script>' . "\n\n";
		
		// Load up that header!
		$this->load->view('header', $header);
		
		// Load the sidebar
		$this->load->view('sidebar-left', $data);
		
		// Load the first part of the edit section
		$data['subtitle'] = $this->lang->line('subtitle_edit_account');
		$this->load->view('edit-top', $data);
		
		// Initialize the idstring var
		$idstring = '';
		
		// Additional data
		$countries = $this->common_model->getCountries();
		
		// Counter var
		$i = 1;

		// Generate editable blocks for each item
		foreach($item_array as $item) {
			// Gather item info
			$row = $this->common_model->getInfo($data['module'], $item);
			
			if($row) {
				if($this->session->userdata('account_type') == 'company') {
					// Check authorization
					$auth = $this->accounts_model->checkAuth($item, $this->session->userdata('client_id'), $row['account_type']);
				} else {
					$auth = $row['account_type'] == 'company' ? true : false;
				}
				
				if($auth) {
					// Assign additional data to be passed
					$row['i'] = $i;
					$row['countries'] = $countries;
					
					// Get company name if admin
					if($this->session->userdata('account_type') == 'site_admin') {
						$row['company'] = $this->accounts_model->getCompanyName($row['id']);
					} else {
						// If agent, get additional info
						if($row['account_type'] == 'agent') {
							$row['agent'] = $this->accounts_model->getAgentInfo($item);
							
							foreach($row['agent']['services']->result_array() as $service) {
								$services[] = $service['client_service_id'];
							}
							
							$row['agent']['services'] = $services;
						}
						
						// Get branches if company, and only display if this is agent account..or display branch name if manager
						if($row['account_type'] == 'manager') {
							$row['branch_name'] = $this->branches_model->getBranchNameByAcct($row['id']);
						} else if($row['account_type'] == 'agent') {
							$row['branches'] = $this->branches_model->getBranchesByClient($this->session->userdata('client_id'));
							$row['services'] = $this->services_model->getServicesByClient($this->session->userdata('client_id'));
						}
					}
					
					// Load the block
					$this->load->view('edit-row-accounts', $row);
						
					// Add to idstring
					$idstring .= ($idstring ? "," . $row['id'] : $row['id']);
					
					// Increment counter
					$i++;
				}
			}
		}
		
		// If no IDs exist, redirect to list
		if(!$idstring) {
			redirect(site_url($data['module']), 'refresh');
		}
		
		// Load the second part of the edit section
		$this->load->view('edit-bottom', array('idstring' => base64_encode($idstring)));
		
		// Let's see that footer!
		$this->load->view('footer');
	}
	
	function edit_ajax() {
		global $data;
		
		// Set module
		$module = $data['module'];
		
		// Generate ID array
		$ids = explode(",", base64_decode($this->input->post("idstring")));
		$error = false;

		foreach($ids as $id) {
			$i = $this->input->post("i" . $id);
			if(is_numeric($id)) {
				if($this->common_model->exists($module, $id)) {
					$info = $this->common_model->getInfo($module, $id);
					
					if($this->session->userdata('account_type') == 'company') {
						// Check authorization
						$auth = $this->accounts_model->checkAuth($id, $this->session->userdata('client_id'), $info['account_type']);
					} else {
						$auth = $info['account_type'] == 'company' ? true : false;
					}
					
					if($auth) {
						// Get additional info if agent
						if($info['account_type'] == 'agent') {
							$info2 = $this->accounts_model->getAgentInfo($id);
						}
						
						$post = array();
	
						$post['first_name'] = $this->input->post("first_name" . $id);
						$post['last_name'] = $this->input->post("last_name" . $id);
						$post['username'] = $this->input->post("username" . $id);
						$post['password'] = $this->input->post("password" . $id);
						$post['confirm'] = $this->input->post("confirm" . $id);
						$post['street_address'] = $this->input->post("street_address" . $id);
						$post['city'] = $this->input->post("city" . $id);
						$post['state'] = $this->input->post("state" . $id);
						$post['country_id'] = $this->input->post("country_id" . $id);
						$post['zip'] = $this->input->post("zip" . $id);
						$post['contact_number'] = $this->input->post("contact_number" . $id);
						$post['email'] = $this->input->post("email" . $id);
						$post['branch_id'] = $this->input->post("branch_id" . $id);
						$post['services'] = $this->input->post("services" . $id);
						
						// Check for duplicates
						$dupe_email = $this->db->select('id')->from('accounts')->where("id != $id AND email = '" . $post['email'] . "'")->get();
						if($info['account_type'] == 'agent') {
							$dupe_username = $this->db->select('a.id')->from('accounts a, agents g')->where("a.id != $id AND a.username = '" . $post['username'] . "' AND g.account_id = a.id AND g.client_id = " . $this->session->userdata('client_id'))->get();
						} else {
							$dupe_username = $this->db->select('id')->from('accounts')->where("id != $id AND username = '" . $post['username'] . "'")->get();
						}
						
						// Check for errors
						$error .= !$post['first_name'] || !$post['last_name'] ? "<li>Provide the account manager's full name for Account $i.</li>" : '';
						$error .= !$post['username'] || strlen($post['username']) < 5 ? "<li>Username must have at least 5 characters for Account $i.</li>" : ($dupe_username->num_rows() > 0 ? "<li>Username is already taken for Account $i.</li>" : '');
						$error .= $post['password'] && strlen($post['password']) < 7 ? "<li>Password must have at least 7 characters for Account $i.</li>" : '';
						$error .= $post['confirm'] != $post['password'] ? "<li>Password and confirmation fields must match for Account $i.</li>" : '';
						$error .= !$post['branch_id'] && $info['account_type'] == 'agent' ? "<li>Select the branch this agent is to be assigned to for Account $i.</li>" : '';
						$error .= empty($post['services']) && $info['account_type'] == 'agent' ? "<li>Select one or more services to assign to this agent for Account $i.</li>" : '';
						$error .= !$post['street_address'] ? "<li>Enter a street address for Account $i.</li>" : '';
						$error .= !$post['city'] ? "<li>Enter a city name for Account $i.</li>" : '';
						$error .= !$post['state'] ? "<li>Enter a state or province for Account $i.</li>" : '';
						$error .= !$post['country_id'] ? "<li>Select a country for this account for Account $i.</li>" : '';
						$error .= !$post['contact_number'] ? "<li>Provide a contact number for this account for Account $i.</li>" : '';
						$error .= !$post['email'] || !validate_email($post['email']) ? "<li>Provide a valid e-mail address for Account $i.</li>" : ($dupe_email->num_rows() > 0 ? "<li>E-mail address is already in use for Account $i.</li>" : '');
		
						
						if(!$error) {
							// Use old password if none provided
							$password = $post['password'] ? md5($post['password']) : $info['password'];
							
							$data = array(
										  'last_name' => $post['last_name'],
										  'first_name' => $post['first_name'],
										  'street_address' => $post['street_address'],
										  'city' => $post['city'],
										  'state' => $post['state'],
										  'country_id' => $post['country_id'],
										  'zip' => $post['zip'],
										  'email' => $post['email'],
										  'contact_number' => $post['contact_number'],
										  'username' => $post['username'],
										  'password' => $password
										 );
							
							$query1 = $this->common_model->update($module, $id, $data);
							$query2 = false;
							
							if($query1 && $info['account_type'] == 'agent') {
								$data = array(
								              'branch_id' => $post['branch_id'],
											  'changed' => 1
											 );
								
								$query2 = $this->common_model->update('agents', false, $data, "account_id = $id");
								$query3 = false;
								
								if($query2) {
									// Add new rows per service association
									foreach($post['services'] as $service) {
										if(!$this->common_model->exists('agents_services', false, "agent_id = $info2[agent_id] AND client_service_id = $service")) {
											$data = array(
														  'agent_id' => $info2['agent_id'],
														  'client_service_id' => $service
														 );
											
											// Add new row if it's on the list
											$query3 = $this->common_model->create('agents_services', $data);
										} else {
											$query3 = true;
										}
									}
									
									$query4 = false;

									if($query3) {
										// Next, delete all associations not in the list
										$str_services = implode(", ", $post['services']);
										$query4 = $this->common_model->delete('agents_services', false, "agent_id = $info2[agent_id] AND client_service_id NOT IN ($str_services)");
									}
								}
							}
							
							if(($info['account_type'] == 'agent' && (!$query1 || !$query2 || !$query3 || !$query4)) || ($info['account_type'] != 'agent' && !$query1)) {
								$error .= "<li>Whoops! Something seems to have gone wrong. Please try again later.</li>";
							}
						}
					}
				}
			}
		}
		
		if($error) {
			echo "<b>Please correct the following errors:</b><br /><ul class='errors'>$error</ul>";
		} else {
			echo "Update successful";
		}
	}
	
	function create() {
		global $header, $data;
		
		// Redirect if administrator
		if($this->session->userdata('account_type') != 'site_admin') {
			// Load local model
			$this->load->model('branches_model');
			$this->load->model('services_model');
			
			// Template variables
			$header['extras'] = '<link href="' . site_url('css/jquery.asmselect.css') . '" rel="stylesheet" type="text/css" />' . "\n" .
								'<script type="text/javascript" src="' . site_url('js/jquery.asmselect.js') . '"></script>' . "\n" .
								'<script type="text/javascript">' . "\n" .
								'// <![CDATA[' . "\n" .
								'  $(document).ready(function() {' . "\n" .
								'    var options = {' . "\n" .
								'        target:         "#response",' . "\n" .
								'        success:        showResponse' . "\n" .
								'    };' . "\n\n" .
								'    $("#theform").ajaxForm(options);' . "\n" .
								'    $("select[multiple]").asmSelect({' . "\n" .
								'        addItemTarget: "bottom",' . "\n" .
								'        animate: true' . "\n" .
								'    });' . "\n" .
								'    function showResponse(responseText, statusText) {' . "\n" .
								'      $("#response").html(responseText).show();' . "\n" .
								'      if(responseText == "Account has been created") {' . "\n" .
								'        $("#response").css("border", "1px solid #c8fb6e");' . "\n" .
								'        $("#response").css("backgroundColor", "#eaffb9");' . "\n" .
								'        window.scrollTo(0,0);' . "\n" .
								'        alert(responseText);' . "\n" .
								'        window.location = "' . site_url($data['module']) . '/";' . "\n" .
								'        //alert(responseText);' . "\n" .
								'      } else {' . "\n" .
								'        $("#response").css("border", "1px solid #fa4646");' . "\n" .
								'        $("#response").css("backgroundColor", "#fabfbf");' . "\n" .
								'        submitted = false;' . "\n" .
								'        window.scrollTo(0,0);' . "\n" .
								'      }' . "\n" .
								'    };' . "\n" .
								'  });' . "\n" .
								'// ]]>' . "\n" .
								'</script>' . "\n\n";
			
			// Load up that header!
			$this->load->view('header', $header);
			
			// Load the sidebar
			$this->load->view('sidebar-left', $data);
			
			// Additional data
			$data['countries'] = $this->common_model->getCountries();
			$data['branches'] = $this->branches_model->getBranchesByClient($this->session->userdata('client_id'));
			$data['services'] = $this->services_model->getServicesByClient($this->session->userdata('client_id'));
			
			// Dish out the meat
			$this->load->view('create-accounts', $data);
			
			// Let's see that footer!
			$this->load->view('footer');
		} else {
			redirect(site_url(), 'refresh');
		}
	}
	
	function create_ajax() {
		$post['first_name'] = $this->input->post("first_name");
		$post['last_name'] = $this->input->post("last_name");
		$post['username'] = $this->input->post("username");
		$post['password'] = $this->input->post("password");
		$post['confirm'] = $this->input->post("confirm");
		$post['street_address'] = $this->input->post("street_address");
		$post['city'] = $this->input->post("city");
		$post['state'] = $this->input->post("state");
		$post['country_id'] = $this->input->post("country_id");
		$post['zip'] = $this->input->post("zip");
		$post['contact_number'] = $this->input->post("contact_number");
		$post['email'] = $this->input->post("email");
		$post['branch_id'] = $this->input->post("branch_id");
		$post['services'] = $this->input->post("services");
		
		$error = false;

		// Check for duplicates
		$dupe_email = $this->db->select('id')->from('accounts')->where("email", $post['email'])->get();
		$dupe_username = $this->db->select('a.id')->from('accounts a, agents g')->where("a.username = '" . $post['username'] . "' AND g.account_id = a.id AND g.client_id = " . $this->session->userdata('client_id'))->get();
		
		// Check for errors
		$error .= !$post['first_name'] || !$post['last_name'] ? "<li>Provide the account manager's full name.</li>" : '';
		$error .= !$post['username'] || strlen($post['username']) < 5 ? "<li>Username must have at least 5 characters.</li>" : ($dupe_username->num_rows() > 0 ? "<li>Username is already taken.</li>" : '');
		$error .= !$post['password'] || strlen($post['password']) < 7 ? "<li>Password must have at least 7 characters.</li>" : '';
		$error .= $post['confirm'] != $post['password'] ? "<li>Password and confirmation fields must match.</li>" : '';
		$error .= !$post['branch_id'] ? "<li>Select the branch this agent is to be assigned to.</li>" : '';
		$error .= empty($post['services']) ? "<li>Select one or more services to assign to this agent.</li>" : '';
		$error .= !$post['street_address'] ? "<li>Enter a street address.</li>" : '';
		$error .= !$post['city'] ? "<li>Enter a city name.</li>" : '';
		$error .= !$post['state'] ? "<li>Enter a state or province.</li>" : '';
		$error .= !$post['country_id'] ? "<li>Select a country for this account.</li>" : '';
		$error .= !$post['contact_number'] ? "<li>Provide a contact number for this account.</li>" : '';
		$error .= !$post['email'] || !validate_email($post['email']) ? "<li>Provide a valid e-mail address.</li>" : ($dupe_email->num_rows() > 0 ? "<li>E-mail address is already in use.</li>" : '');
		
		if(!$error) {
			$data = array(
						  'last_name' => $post['last_name'],
						  'first_name' => $post['first_name'],
						  'street_address' => $post['street_address'],
						  'city' => $post['city'],
						  'state' => $post['state'],
						  'country_id' => $post['country_id'],
						  'zip' => $post['zip'],
						  'email' => $post['email'],
						  'contact_number' => $post['contact_number'],
						  'username' => $post['username'],
						  'password' => md5($post['password']),
						  'account_type' => 'agent'
						 );
						 
			$query1 = $this->common_model->create('accounts', $data);
			$query2 = false;
			
			if($query1) {
				$data = array(
							  'account_id' => $query1,
							  'client_id' => $this->session->userdata('client_id'),
							  'branch_id' => $post['branch_id']
							 );
				
				$query2 = $this->common_model->create('agents', $data);
				$branch_name = $this->common_model->getName('branches', $post['branch_id']);
				$query3 = false;
				
				if($query2) {
					foreach($post['services'] as $service) {
						$data = array(
									  'agent_id' => $query2,
									  'client_service_id' => $service
					    			 );
						
						$query3 = $this->common_model->create('agents_services', $data);
					}
				}
			}
			
			if(!$query1 || !$query2 || !$query3) {
				$error .= "<li>Whoops! Something seems to have gone wrong. Please try again later.</li>";
			}
		}
		
		if($error) {
			echo "<b>Please correct the following errors:</b><br /><ul class='errors'>$error</ul>";
		} else {
			// Send confirmation e-mail
			$this->email->from('noreply@queue-systems.com', $this->lang->line('app_title'));
			$this->email->to($post['email']);
			$this->email->subject($this->lang->line('signup_email_subject'));
			$this->email->message($this->lang->line('signup_email_body_head') . "\r\n\r\n" .
								  $this->lang->line('signup_company_name') . ': ' . $this->session->userdata('company_name') . "\r\n" .
								  $this->lang->line('branch_name') . ': ' . $branch_name . "\r\n\r\n" .
								  $this->lang->line('username') . ': ' . $post['username'] . "\r\n" .
								  $this->lang->line('password') . ': ' . $post['password'] . "\r\n\r\n" .
								  $this->lang->line('local_email_body_foot'));
			$this->email->send();
			
			echo "Account has been created";
		}
	}
	
	function del() {
		// Retrieve post var
		$id = $this->input->post("ids");

		// Get item info
		$info = $this->common_model->getInfo('agents', $id, "id", "account_id = $id");
			
		if($info) {
			// Run the delete query
			$query1 = $this->common_model->delete('agents', $info['id']);
			$query2 = $this->common_model->delete('accounts', $id);
			
			// Return results
			if($query1 && $query2) {
				//$this->logs_model->add($this->session->userdata("user_id"), 1, 0, 0, $this->session->userdata('post_id'), 'Deleted Announcement (' . $info['title'] . ')');
				echo "Deletion was successful.";
			} else {
				echo "Error deleting the selected row. Please try again later.";
			}
		} else {
			echo "This item does not exist in the database.";
		}
	}
}